<?php
/**
 * @name User
 * @package: User
 * @package public
 * @author Truonghm
 * @version $1.0
 * @license http://officex.vn/license
 * @copyright ecommerce.
 * 30/10/2010
 * cac ham nghiep vu lien quan den user
 * 
 */
class User_Models_Business_User extends User_Models_Interface_User {
	
	/**
	 * @deprecated deprecated
	 * @param $arr
	 * @return reer
	 */
	protected function doLogin($json) 
	{		
		$loginInfo = Zend_Json::decode($json, Zend_Json::TYPE_OBJECT);
		//1.Goi ket noi voi Zend Db
		$db = Zend_Registry::get('db');
			
		//2. Khoi tao Zend Autho
		$auth = Zend_Auth::getInstance();
		
		//3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
		$authAdapter = new Zend_Auth_Adapter_DbTable ($db);
		$authAdapter->setTableName('user')
				    ->setIdentityColumn('username')
				    ->setCredentialColumn('password');
		
		//4. Lay gia tri duoc gui qua tu FORM
		$username = $loginInfo->username;
		$password = $loginInfo->password;
		
		//5. Dua vao so sanh voi du lieu khai bao o muc 3
		$authAdapter->setIdentity($username);
		$authAdapter->setCredential(md5($password));
		
		//6. Kiem tra trang thai cua user neu active = 1 moi duoc login
		$select = $authAdapter->getDbSelect();		
		$select->where('active = 1');
		
		
		//7. Lay ket qua truy van
		$result = $auth->authenticate($authAdapter);
		
		if($result->isValid()){
			$flag["success"] = true;
			$flag["errors"] = '';
			//8. Lay nhung du lieu can thiet trong bang users neu login thanh cong
			//lu vao Zend_auth. bo qua truong mat khau				
			$data = $authAdapter->getResultRowObject (null,array('password'));			
		
			//9. Luu  nhung du lieu cua member vao session
			$auth->getStorage()->write($data);
			
			//get all privilage user and ser to session
			$this->getPrivilege();
		}
		else
		{
			$flag["success"] = false;
			$flag["errors"] = 'username/password false';
		}
		
		return $flag;
	}
	/**
	 * 
	 * Insert user
	 * @arr: key= column name, vaule = insert value
	 * @VD: 'name' => 'document'
	 * @return: object type
	 * 	arr( 
	 * 		'success'=>'true/false'
	 * 		,'errors'=>'info errors'// err code
	 * 
	 */
	protected function doInsert($json)
	{
		$obj = Zend_Json::decode($json, Zend_Json::TYPE_OBJECT);
		$translate=Zend_Registry::get('translate');
		
		$db = Zend_Registry::get('db');
		
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getIdentity();
				
		try {
			$db->beginTransaction();
						
			//check exitst user
			$cls_user = new Models_User();
			$vc_select =$cls_user->select()
						   		 ->where('username = ?',$obj->fix->username);			
			$obj_user = $cls_user->fetchRow($vc_select);			
			
			if(isset($obj_user->id) > 0){			
				$flag["success"] = false;
				$flag["errors"] = $translate->translate("Exist member");	
				return $flag;
			}
			
			$data = (array)$obj->columns;			
			$data["password"] = md5($obj->fix->password);			
			$data["created_by"] = $userInfo->username;			
			$data["created_date"] = new Zend_Db_Expr('SYSDATE()');			
			
			$insert_id = $cls_user->insert($data);
			
			//insert role
			$role_id = $obj->exception->role_id;
			
			if($role_id){
				$data = array(
					 "user_id"=>$insert_id
					,"role_id"=>$role_id
				);
				$table = new Models_UserRole();
				$result= $table	->insert($data);
			}
			$db->commit();
			
			$flag["success"] = true;
			$flag["errors"] = "";			
		} catch (Exception $e){
			$db->rollBack();
			$flag["success"] = false;
			$flag["data"]["errors"] = $e->getMessage();
		}
		return Zend_Json::encode($flag);
	}
	
	/*
	 * 
	 * Update user
	 * @arr: key= column name, vaule = update value
	 * @VD: 'name' => 'document'
	 * @note: chi update nhung column nao co trong mang truyen vao
	 * 		  cac column kha co trong data nhung khong co trong mang truyen vao khong thay doi gia tri
	 * @return: object type 
	 * 
	 */
	protected function doUpdate($json)
	{
		$obj = Zend_Json::decode($json, Zend_Json::TYPE_OBJECT);
		
		$db = Zend_Registry::get('db');
				
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getIdentity();		
				
		$edit_id = $obj->columns->id;
		
		try {	
			$db->beginTransaction();
			
			$data = (array)$obj->columns;
			
			$data["updated_by"]=$userInfo->username;
			$data["updated_date"]= new Zend_Db_Expr('SYSDATE()');	
			
			
			$table = new Models_User();
			$where = $table->getAdapter()->quoteInto('id = ?', $edit_id);
			$result = $table->update($data,$where);
			
			$data = array(
				 "user_id"=>$edit_id
				,"role_id"=>$obj->exception->role_id
			);
			$table = new Models_UserRole();
			
			$where = $table->getAdapter()->quoteInto('user_id = ?', $edit_id);			
			$result= $table	->delete($where);
			
			$result= $table	->insert($data);
			
			$db->commit();
			
			$flag["success"] = true;
			
		} catch (Exception $e){
			$db->rollBack();
			$flag["success"] = false;
			$flag["data"]["errors"] = $e->getMessage();
		}
		
		return Zend_Json::encode($flag);
	}
	
	/**
	 * Delete user 
	 * @param $userId 
	 * @return: object type 
	 */
	
	protected function doDelete($userId)
	{
		$db = Zend_Registry::get('db');
		try {	
			$db->beginTransaction();
			
			$data = array(
				 "del"=>1
				,"active"=>0
			);
			
			$table = new Models_User();
			$where = $table->getAdapter()->quoteInto('id = ?', $userId);
			$result = $table->update($data,$where);
			
			$db->commit();
			
			$flag["success"] = true;
						
		} catch (Exception $e){
			$db->rollBack();
			$flag["success"] = false;
			$flag["errors"] = $e->getMessage();
		}
		return Zend_Json::encode($flag);
	}
	
	/**
	 * @param $userId	 
	 * @return json data rows user {"success":true,"data":{....}}
	 * @desc get info user thong qua id
	 */
	protected function doPrimarykey($userId)
	{
		try {
			$lblUser = new Models_User();		
			$data = $lblUser->find($userId);
			$info_user = $data->current()->toArray();
			
			$lblUserRole = new Models_UserRole();
			$select = $lblUserRole->select()
								  ->where('user_id = :userId')
								  ->bind(array(':userId'=>$userId));
			
			$data = $lblUserRole->fetchAll($select);
			if($data->current())
			{		
				$result = $data->current()->toArray();
				$info_user["role_id"]=$result["role_id"];
			}		
			
			$flag["success"] = true;
			$flag["data"] = $info_user;
		} catch (Exception $e){
			$flag["success"] = false;
			$flag["errors"] = $e->getMessage();
		}
		return 	Zend_Json::encode($flag);	  
	}
	
	
	/**
	 * danh sach thanh vien
	 * @param $start
	 * @param $limit
	 * @return Array("count": count record, "data": array data)
	 */
	protected function doGetList($json)
	{
		$data = Zend_Json::decode($json, Zend_Json::TYPE_OBJECT);
		$limit = $data->limit;
		$start = $data->start;
		$query = $data->query;
		
		$model = new Models_User();
		$select = $model->select()
						->where('username like \'%'.$query.'%\'')
						//->bind(array(':del'=>0))
						->order('created_date DESC')
						->limit($limit,$start);

		$flag["count"] = $this->getUserCount($query);
		$flag["data"]=$model->fetchAll($select)->toArray();
		return Zend_Json::encode($flag);
	}
	/**
	 * Tong so thanh vien co trong he thong
	 * return number
	 */
	protected function getUserCount($query=null){
		$table = new Models_User();
		$select = $table->select()
						->where('username like \'%'.$query.'%\'')
						//->bind(array(':del'=>0))
					    ->from($table,'COUNT(*) AS count');		
		$row=$table->fetchRow($select);
		return $row->count;
	}
	
	/**
	 * danh sach privilage cua thanh vien hien tai theo role
	 * return array
	 * [0] => Array
     *   (
     *       [id] => 1
     *       [module_name] => user
     *       [controller_name] => index
     *       [action_name] => index
     *       [function_name] => doEdit();
     *       [name] => edit
     *   )
	 */
	protected function getPrivilege()
	{
		$auth = Zend_Auth::getInstance();
		//id user dang login
		$userId = $auth->getIdentity()->id;
		
		$session = Zend_Registry::get('session');		
		
		if(!$userId || $session->privilege) return;
		
		$lblUser = new Models_User();
		$lblUserRole = new Models_UserRole();
		$lblRole = new Models_Role();
		$lblRoleMenuPrivilege = new Models_RoleMenuPrivilege();
		$lblMenuPrivilege = new Models_MenuPrivilege();
		$lblMenu = new Models_Menu();
		$lblPrivilege = new Models_Privilege();
		$lblUserMenuPrivilege = new Models_UserMenuPrivilege();
		//return;
		//Lay toan bo privilage cua thanh vien khong thuoc role
		$select = $lblUser->select()
						->setIntegrityCheck(false)
						->from(array("u"=>$lblUser->info("name")) ,"id")
						->joinInner(array("ur"=>$lblUserRole->info("name")),"u.id =ur.user_id",array())
						->joinInner(array("r"=>$lblRole->info("name")),"ur.role_id = r.id",array())
						->joinInner(array("rmp"=>$lblRoleMenuPrivilege->info("name")),"r.id =  rmp.role_id",array())
						->joinInner(array("mp"=>$lblMenuPrivilege->info("name")),"rmp.menu_privilege_id =  mp.id",array())
						->joinInner(array("m"=>$lblMenu->info("name")),"mp.menu_id =  m.id",array("m.module_name","m.controller_name","m.action_name"))
						->joinInner(array("p"=>$lblPrivilege->info("name")),"mp.privilege_id =  p.id", array("p.function_name","p.name","p.display_name","p.icon"))
						->where("u.id=?",$userId);
		$arrPrivilege = $lblUser->fetchAll($select)->toArray();
		
		//lay toan bo privilage cua thanh vien theo role
		$select = $lblUser->select()
						->setIntegrityCheck(false)
						->from(array("u"=>"user") ,"id")
						->joinInner(array("ump"=>$lblUserMenuPrivilege->info("name")),"u.id =  ump.user_id",array())
						->joinInner(array("mp"=>$lblMenuPrivilege->info("name")),"ump.menu_privilege_id =  mp.id",array())
						->joinInner(array("m"=>$lblMenu->info("name")),"mp.menu_id =  m.id",array("m.module_name","m.controller_name","m.action_name"))
						->joinInner(array("p"=>$lblPrivilege->info("name")),"mp.privilege_id =  p.id", array("p.function_name","p.name","p.display_name","p.icon"))
						->where("u.id=?",$userId);
		$arrPrivilegeRole = $lblUser->fetchAll($select)->toArray();
		
		//Tap hop privilage vao $arrPrivilage
		if($arrPrivilegeRole)
		foreach($arrPrivilegeRole as $k=>$v) $arrPrivilege[]=$v;
		
		//gan $arrPrivilege vao session privilege
		$session->privilege = $arrPrivilege;
		return $arrPrivilege;
	}	
	
	
	/**
	 * lock user 
	 * @param $userId 
	 * @return: object type 
	 */
	
	protected function doLock($userId)
	{
		$db = Zend_Registry::get('db');
		try {	
			$db->beginTransaction();
			
			$data = array(
				 "del"=>0
				,"active"=>0
			);
			
			$table = new Models_User();
			$where = $table->getAdapter()->quoteInto('id = ?', $userId);
			$result = $table->update($data,$where);
			
			$db->commit();
			
			$flag["success"] = true;
						
		} catch (Exception $e){
			$db->rollBack();
			$flag["success"] = false;
			$flag["errors"] = $e->getMessage();
		}
		return Zend_Json::encode($flag);
	}
	
/**
	 * lock user 
	 * @param $userId 
	 * @return: object type 
	 */
	
	protected function doUnlock($userId)
	{
		$db = Zend_Registry::get('db');
		try {	
			$db->beginTransaction();
			
			$data = array(
				 "del"=>0
				,"active"=>1
			);
			
			$table = new Models_User();
			$where = $table->getAdapter()->quoteInto('id = ?', $userId);
			$result = $table->update($data,$where);
			
			$db->commit();
			
			$flag["success"] = true;
						
		} catch (Exception $e){
			$db->rollBack();
			$flag["success"] = false;
			$flag["errors"] = $e->getMessage();
		}
		return Zend_Json::encode($flag);
	}
}

?>